package com.weai.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;

@Slf4j
@Service
public class ReportService {

    private static final String WIN_PATH = "C:\\Users\\Administrator\\Documents\\reports";
    private static final String LINUX_PATH = "/data/app/deposit_system/reports";

    private String getBasePath() {
        String os = System.getProperty("os.name").toLowerCase();
        String path = os.contains("win") ? WIN_PATH : LINUX_PATH;
        File dir = new File(path);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            log.info("目录{}不存在，已自动创建: {}", path, created);
        }
        return path;
    }

    public void saveReportFile(MultipartFile file) throws IOException {
        String basePath = getBasePath();
        String filename = file.getOriginalFilename();
        if (filename == null || !filename.endsWith(".html")) {
            throw new IOException("只允许上传HTML文件");
        }
        File dest = new File(basePath, filename);
        try (InputStream in = file.getInputStream();
             OutputStream out = new FileOutputStream(dest)) {
            in.transferTo(out);
        }
        log.info("文件已保存到: {}", dest.getAbsolutePath());
    }

    public List<String> listReportFiles() {
        String basePath = getBasePath();
        File dir = new File(basePath);
        String[] files = dir.list((d, name) -> name.endsWith(".html"));
        if (files == null) return Collections.emptyList();
        return Arrays.asList(files);
    }

    public String getReportFileContent(String filename) throws IOException {
        String basePath = getBasePath();
        File file = new File(basePath, filename);
        if (!file.exists() || !file.getName().endsWith(".html")) {
            throw new FileNotFoundException("文件不存在或不是HTML文件");
        }
        return Files.readString(file.toPath(), StandardCharsets.UTF_8);
    }
} 